package com.ruoyi.common.utils.file;

import com.ruoyi.common.utils.uuid.UUID;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件处理工具类
 * 
 * @author ruoyi
 */
public class FileUtils extends org.apache.commons.io.FileUtils
{
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     * 
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     * 
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     * 
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     * 
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }


    /**
     * 指定线程数
     */
    private static final Integer THREAD_NUM = 2;

    /**
     * 断点续传
     *
     * @param sourceStr 目标文件地址
     * @param targetStr 存放地址
     */
    public static void breakpointResume(String sourceStr, String targetStr) {
        File dataFile = new File(sourceStr);
        long length = dataFile.length();
        //每个线程均分文件大小，且向上取整
        long part = (long) Math.ceil(length / THREAD_NUM);
        //线程减法计数器
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
        Instant beginTime = Instant.now();
        //记录传输的日志文件
        File logFile = new File(targetStr + ".log");
        String[] splitData = null;//不是null就需要断点续传
        BufferedReader reader = null;
        try {
            if (logFile.exists()) {
                //存在日志文件，需要进行断点续传
                reader = new BufferedReader(new FileReader(logFile));
                String data = reader.readLine();
                splitData = data.split(",");
            } else {
                //不存在日志文件，创建日志文件
                logFile.createNewFile();
            }
            Map<Integer, Long> maps = new ConcurrentHashMap<>();
            for (int i = 0; i < THREAD_NUM; i++) {
                final int k = i;
                System.out.println("线程正在执行任务：" + k);
                String[] finalData = splitData;
                new Thread(() -> {
                    RandomAccessFile inFile = null;
                    RandomAccessFile outFile = null;
                    RandomAccessFile rafLog = null;
                    try {
                        inFile = new RandomAccessFile(dataFile, "r");//读
                        outFile = new RandomAccessFile(targetStr, "rw");//写
                        rafLog = new RandomAccessFile(logFile, "rw");//操作日志文件的流
                        //确定每个线程读取文件的开始和结束的位置,有断点续传就从日志文件取出的位置开始读取
                        inFile.seek(finalData == null ? k * part : Long.parseLong(finalData[k]));//设置每个线程读取的启始位置
                        outFile.seek(finalData == null ? k * part : Long.parseLong(finalData[k]));//设置每个线程写入的启始位置
                        byte[] bytes = new byte[1024 * 10];//每次读取字节大小
                        int len = -1, allLen = 0;
                        while (true) {
                            len = inFile.read(bytes);//从磁盘读取到缓存
                            if (len == -1) { //数据读完，结束
                                break;
                            }
                            //如果不等于 -1，把每次读取的字节累加
                            allLen = allLen + len;
                            //将读取的字节数放入到map中
                            maps.put(k, allLen + (finalData == null ? k * part : Long.parseLong(finalData[k])));//每个线程的绝对偏移量
                            outFile.write(bytes, 0, len);//从缓存写入到磁盘
                            //将map中的字节日志信息数据写入磁盘
                            StringJoiner stringJoiner = new StringJoiner(",");
                            maps.forEach((key, value) -> stringJoiner.add(String.valueOf(value)));
                            //将日志信息写入磁盘
                            rafLog.seek(0);//覆盖之前的日志信息
                            rafLog.write(stringJoiner.toString().getBytes("UTF-8"));
                            /**
                             * 当前线程读取的内容
                             *  allLen + (k * part)
                             *  或
                             *  allLen + finalData[k] 日志文件里面的偏移量
                             *  >=
                             *  下个线程的起始部分((k + 1) * part)
                             *  当前线程就不再读取写入数据，结束任务
                             */
                            if (allLen + (finalData == null ? k * part : Long.parseLong(finalData[k])) >= (k + 1) * part) {
                                break;
                            }
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        //关流
                        if (null != outFile && null != inFile && null != rafLog) {
                            try {
                                outFile.close();
                                inFile.close();
                                rafLog.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        countDownLatch.countDown();//减一
                    }
                }).start();
            }

            //主线程要等到线程计数器归零，再继续往下执行
            countDownLatch.await();
            Instant endTime = Instant.now();
            System.out.println("总耗时：" + (Duration.between(beginTime, endTime).toMillis()) + "毫秒");
            //删除日志文件
            logFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 支持自动断点续传的下载方法
     *
     * @param urlStr 网络资源的url
     */
    public static void downloadResource(String urlStr) {
        long startPosition = 0;
        long endPosition = 0;
        try {
            URL url = new URL(urlStr);// 获得网络资源的URL
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();// 获得连接对象
            String file = url.getFile();// 获得文件对象
            String name = file.substring(file.lastIndexOf('/') + 1);// 获得文件名
            File fileOb = new File(name);
            //判断是否是暂停下载的文件
            if (fileOb.exists()) {
                startPosition = fileOb.length();
                endPosition = getResourceLength(urlStr);
            }
            connection.setRequestProperty("User-Agent", "NetFox");// 设置请求属性
            String rangeProperty = "bytes=" + startPosition + "-";// 定义请求范围属性
            if (endPosition > 0) {
                rangeProperty += endPosition;// 调整请求范围属性
            }
            connection.setRequestProperty("RANGE", rangeProperty);// 设置请求范围属性
            connection.connect();// 连接网络资源
            InputStream in = connection.getInputStream();// 获得输入流对象
            FileOutputStream out = new FileOutputStream(name, true);// 创建输出流对象,保存下载的资源
            byte[] buff = new byte[2048];// 创建字节数组
            int len = 0;// 定义存储读取内容长度的变量
            len = in.read(buff);// 读取内容
            while (len != -1) {
                out.write(buff, 0, len);// 写入磁盘
                len = in.read(buff);// 读取内容
            }
            out.close();// 关闭流
            in.close();// 关闭流
            connection.disconnect();// 断开连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给定url地址获取资源的大小（以字节为单位）
     *
     * @param urlStr
     * @return
     * @throws IOException
     */
    public static long getResourceLength(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        return urlConnection.getContentLength();
    }



    private void zipDownload(HttpServletResponse response, String path, String zipFileName, List<File> fileList) {
        String zipPath = path + zipFileName;
        try {
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
                byte[] buffer = new byte[1024 * 2];
                for (File file : fileList) {
                    try (FileInputStream fis = new FileInputStream(file)) {
                        out.putNextEntry(new ZipEntry(file.getName()));
                        int len;
                        while ((len = fis.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        out.closeEntry();
                    }
                }
            }
            downFile(response, path, zipFileName);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载出错" + e);
        } finally {
            fileList.add(new File(zipPath));
        }
    }

    public static void downFile(HttpServletResponse response, String path, String zipFileName) {
        try {
            String realPath = path + zipFileName;
            File file = new File(realPath);
            if (!file.exists()) {
                throw new Exception(zipFileName + "文件不存在");
            }
            try (BufferedInputStream bins = new BufferedInputStream(new FileInputStream(realPath));
                 OutputStream outs = response.getOutputStream();
                 BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
//                response.setContentType("application/x-download");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Length",""+file.length());
                response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(zipFileName, "UTF-8"));
                response.setHeader("fileName", URLEncoder.encode(zipFileName, "UTF-8"));
                int bytesRead = 0;
                byte[] buffer = new byte[1024 * 1024];
                while ((bytesRead = bins.read(buffer, 0, 1024 * 1024)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载出错" + e);
        }
    }

    public static void downFile(HttpServletResponse response, InputStream inputStream, String fileName,Integer fileSize) {
        try {
            try (BufferedInputStream bins = new BufferedInputStream(inputStream);
                 OutputStream outs = response.getOutputStream();
                 BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
//                response.setContentType("application/x-download");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Length",""+fileSize);
                response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setHeader("fileName", URLEncoder.encode(fileName, "UTF-8"));
                int bytesRead = 0;
                byte[] buffer = new byte[1024 * 2];
                while ((bytesRead = bins.read(buffer, 0, 1024 * 2)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载出错" + e);
        }
    }


    /**
     * 获取对应的contentType
     * @param fileName
     * @return
     */
    public static String getContentType(String fileName){
        String ext = "";
        String contentType="";
        //获取后缀
        if(!"".equals(fileName) && fileName.contains(".")){
            ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
        }

        //类型
        if ("png".equals(ext) || "jpeg".equals(ext) || "jpg".equals(ext)) {
            contentType="image/jpeg";
        }
        if ("bmp".equals(ext)) {
            contentType="image/bmp";
        }
        if ("pdf".equals(ext)) {
            contentType="application/pdf";
        }
        return contentType;
    }
    /**
     * 判断附件是否是图片
     * @param filename
     * @return
     */
    public static boolean isImage(String filename){
        String suff=filename.substring(filename.lastIndexOf(".")+1);//后缀名
        suff=suff.toLowerCase();
        if("jpg".equals(suff)||"jpeg".equals(suff)||"gif".equals(suff)||"png".equals(suff)){
            return true;
        }else{
            return false;
        }
    }
    public static String getFolder(){
        SimpleDateFormat formatYear=new SimpleDateFormat("yyyy");
        SimpleDateFormat formatMonth=new SimpleDateFormat("MM");
        SimpleDateFormat formatDay=new SimpleDateFormat("dd");
        String year=formatYear.format(new Date());
        String month=formatMonth.format(new Date());
        String day=formatDay.format(new Date());

        String folder=year+"/"+month+"/"+day;
        return folder;
    }

    /**
     * 获取真实名称
     * @author 郑伟业
     * 2018年10月22日
     * @param fileName
     * @return
     */
    public static String getRealName(String fileName){
        if(fileName==null||"".equals(fileName)){
            throw new RuntimeException("fileName不能为空");
        }else{
            if(!fileName.contains(".")){
                throw new RuntimeException("fileName格式不对");
            }
        }
        fileName=fileName.replaceAll("\\\\","/");
        if(fileName.contains("/")){
            String[] names=fileName.split("/");
            fileName=names[names.length-1];
        }
        return fileName;
    }
    /**
     * 获取存储文件系统的真实名称
     * @author 郑伟业
     * 2018年10月22日
     * @param filename
     * @return
     */
    public static String getSaveName(String filename){
        String suff=filename.substring(filename.lastIndexOf(".")+1);//后缀名
        return UUID.randomUUID().toString()+"."+suff;
    }

    /**
     * 获取转换后缀名称
     * @param filename
     * @param convertSuffix
     * @return
     */
    public static String getConvertName(String filename,String convertSuffix){
        String name=filename.substring(0, filename.lastIndexOf("."));
        return name+"."+convertSuffix;
    }

    /**
     * 获取文件-后缀
     * @author 郑伟业
     * 2018年10月21日
     * @param filename
     * @return
     */
    public static String getFileSuffix(String filename){
        String suff=filename.substring(filename.lastIndexOf(".")+1);//后缀名
        suff=suff.toLowerCase();
        return suff;
    }

    /**
     * @category 获取附件大小
     * @param l
     * @return
     */
    public static String getFileSize(long l){
        long d=l/1024;
        if(d<1024){
            return d+"kb";
        }else if(d>1024&&d<1024*1024){
            return d/1024+"mb";
        }else{
            return d/(1024*1024)+"gb";
        }
    }


    /**
     * 删除指定文件夹下文件
     *
     * @param filePath
     */
    public static void deleteFolders(String filePath) {

        Path path = Paths.get(filePath);
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                    Files.delete(file);
                    System.out.printf("删除文件: %s", file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                                                          IOException exc) throws IOException {
                    Files.delete(dir);
                    System.out.printf("文件夹被删除: %s", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
